function loadCourseData() {
    // 调用 API 获取学生数据
    $.ajax({
        url: "http://localhost:8080/course/list", // 替换为你的API地址
        method: "GET",
        dataType: "json",
        contentType: "application/json",
        cache: false,
        success: function (response) {
            // 清空学生表格数据
            $("#courses-tbody").empty();

            // 遍历后端返回的学生数组
            $.each(response.data, function (index,course) {
                // 生成表格行 HTML
                let courseRowHTML = `<tr>
                    <td>${course.id}</td>
                    <td>${course.co_name}</td>
                    <td>${course.co_major}</td>
                    <td>${course.status}</td>
                    <td>${course.book}</td>
                     <td>
                    <button class="btn btn-sm btn-primary" data-course-id="${course.id}">编辑</button>
                    <button class="btn btn-sm btn-danger" data-course-id="${course.id}">删除</button>
                    </td>
                    </tr>`;

                // 将表格行添加到表格中
                $("#courses-tbody").append(courseRowHTML);
            });
        },
        error: function (error) {
            // 如果出现错误，弹出错误消息
            console.error("获取学生数据失败：", error);
        }
    });
}

/**
 * 初始化课程表格
 */
function initializeCourseTable() {
    loadCourseData();

    // 清空课程输入框
    function resetForm() {
        $("#course-name").val("");
        $("#course-major").val("");
        $("#course-delivery").val("");
        $("#course-textbook").val("");
    }

    $("#add-course-btn").click(function () {
        console.log("添加课程按钮被点击");

        var course_name = $("#course-name").val();
        var course_major = $("#course-major").val();
        var course_delivery = $("#course-delivery").val();
        var course_textbook = $("#course-textbook").val();

        if (course_name === "" || course_major === "" || course_delivery === "" || course_textbook === "") {
            alert("输入不能为空！");
            return;
        }

        $.ajax({
            url: "http://localhost:8080/course/add",
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            cache: false,
            data: JSON.stringify({
                "co_name": course_name,
                "co_major": course_major,
                "status": course_delivery,
                "book": course_textbook
            }),
            success: function (response) {
                if (response.message == "ok")
                {
                    alert("添加成功！");
                    resetForm();
                    loadCourseData();
                }
                else
                {
                    alert(response.message);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                alert("添加课程处理过程中发生问题！");
            }
        });
    });

    // 删除课程
    $("#courses-tbody").on("click", ".btn-danger", function () {
        console.log("删除课程按钮被点击");
        let courseId = $(this).data("course-id");

        // 确认是否要删除
        if (!confirm("确定要删除此课程吗？")) {
            return;
        }

        // 调用后端 API 以删除课程
        $.ajax({
            url: `http://localhost:8080/course/delete/${courseId}`,
            method: "DELETE",
            dataType: "json",
            contentType: "application/json",
            cache: false,
            success: function (response) {
                if (response.message == "ok") {
                    alert("课程已删除！");
                    // 重新加载课程数据
                    loadCourseData();
                } else {
                    alert("删除失败: " + response.message);
                }
            },
            error: function (error) {
                console.error("删除课程失败：", error);
            }
        });
    });
    // 编辑课程
    $("#courses-tbody").on("click", ".btn-primary", function () {
        // 获取当前行的课程数据
        let courseRow = $(this).parent().parent();
        let courseId = $(this).data("course-id");
        let courseName = courseRow.children().eq(1).text();
        let courseMajor = courseRow.children().eq(2).text();
        let courseDelivery = courseRow.children().eq(3).text();
        let courseTextbook = courseRow.children().eq(4).text();

        // 在模态框中设置课程数据
        $('#edit-course-id').val(courseId);
        $('#edit-course-name').val(courseName);
        $('#edit-course-major').val(courseMajor);
        $('#edit-course-delivery').val(courseDelivery);
        $('#edit-course-textbook').val(courseTextbook);

        // 显示模态框
        $('#editCourseModal').modal('show');
    });

// 保存编辑后的课程数据
    $('#saveCourseChangesBtn').click(function () {
        let courseId = $('#edit-course-id').val();
        let courseName = $('#edit-course-name').val();
        let courseMajor = $('#edit-course-major').val();
        let courseDelivery = $('#edit-course-delivery').val();
        let courseTextbook = $('#edit-course-textbook').val();

        // 发送更新请求给后端 API
        updateCourseData(courseId, courseName, courseMajor, courseDelivery, courseTextbook);

        // 隐藏模态框
        $('#editCourseModal').modal('hide');
    });

    /**
     * 更新课程数据的函数
     * @param courseId
     * @param courseName
     * @param courseMajor
     * @param courseDelivery
     * @param courseTextbook
     */
    function updateCourseData(courseId, courseName, courseMajor, courseDelivery, courseTextbook) {
        // 通过 AJAX 向后端发送更新请求
        $.ajax({
            url: `http://localhost:8080/course/edit/${courseId}`,
            method: "PUT",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({
                "co_name": courseName,
                "co_major": courseMajor,
                "status": courseDelivery,
                "book": courseTextbook
            }),
            cache: false,
            success: function (response) {
                if (response.message == "ok") {
                    alert("更新成功！");
                    // 请求成功，重新加载课程数据
                    loadCourseData();
                } else {
                    alert("更新失败: " + response.message);
                }
            },
            error: function (error) {
                console.error("更新课程数据失败：", error);
            }
        });
    }

}



function bindCourseTableEvents() {
    initializeCourseTable();
}
